package com.lee.app.controller;


import com.lee.app.entity.User;
import com.lee.app.service.UserService;
import com.lee.app.util.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



/**
 * @author Lee
 */
@RestController
@RequestMapping("api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public String login(User user) {
        User result = userService.login(user);
        if (result != null) {
            return JacksonUtil.build(1, "登录成功", result);
        } else {
            return JacksonUtil.build(0, "登录失败");
        }
    }

    @RequestMapping("list")
    public String list() {
        return JacksonUtil.build(userService.list());
    }

    @RequestMapping("insert")
    public String insert(User user, Integer[] roleIds) {
        userService.insert(user, roleIds);
        return JacksonUtil.build(1, "添加成功");
    }

    @RequestMapping("select-by-id")
    public String selectById(Integer id) {
        User user = userService.selectById(id);
        if (user != null) {
            return JacksonUtil.build(user);
        }
        return JacksonUtil.build(0, "查询失败");
    }

    @RequestMapping("update-by-id")
    public String updateById(User user, Integer[] roleIds) {
        userService.updateById(user, roleIds);
        return JacksonUtil.build(1, "修改成功");
    }

    @RequestMapping("delete-by-id")
    public String deleteById(Integer id) {
        try{ if (id == null) {
            return JacksonUtil.build(0, "用户主键不存在");
        }

        userService.deleteById(id);
        return JacksonUtil.build(1, "删除成功");}
        catch (Exception e){
            return JacksonUtil.build(0, "用户主键不存在");
        }
    }
}
